//
//  MsgEngine.m
//  MobileMeeting
// @""
//  Created by Woo Jack on 13-5-30.
//  Copyright (c) 2013年 chenxiaojuan. All rights reserved.
//

#import "MsgEngine.h"
#import "Class+Plugins.h"
#import "MessageSessionDao.h"
#import "Message.h"

@interface MsgEngine (){
    NSString* _msgServerName;
    NSString* _msgServerPort;
    MosquittoClient* mosquittoClient;
}

//@property(nonatomic,retain)NSString* state;

@end

@implementation MsgEngine



-(id)init
{
    if ( self = [super init] )
    {
        kAppDelegate.mqttState = MQTT_NO_CONNECT;
    }
    return self;
}

-(void)dealloc
{
    [_msgServerName release];
    [_msgServerPort release];
    [mosquittoClient release];
    [super dealloc];
}

-(void)reconnect
{
    NSLog(@"MQ is reconnecting>>>>>>>>");
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    kAppDelegate.mqttState = MQTT_CONNECT_ING;
    if ( mosquittoClient )
    {
        [mosquittoClient disconnect];
        [mosquittoClient release];
        mosquittoClient = nil;
    }
    mosquittoClient = [[MosquittoClient alloc] initWithClientId:[MsgEngine geMessageClientID]];
    mosquittoClient.host = self.msgServerName;
    mosquittoClient.port = [self.msgServerPort intValue];
    [mosquittoClient setDelegate:self];
    [mosquittoClient connect];
}

-(void)disconnect
{
    if ( mosquittoClient )
    {
        [mosquittoClient disconnect];
        [mosquittoClient release];
        mosquittoClient = nil;
    }
    kAppDelegate.mqttState = MQTT_NO_CONNECT;
}

/**
 MQTT的消息接收处理
 */
-(void)recvMqttMessage:(NSString*)text
{
    NSLog(@"real time mqtt arrive--->>>>>>");
    NSDictionary* response = [ServerEngine decodeCmd:text];
    NSArray *msglist =[[response objectForKey:@"data"] objectForKey:@"RECORDS"];
    // 收到就签收掉
    NSMutableArray *receiptMsgIDs = [[NSMutableArray alloc] init];
        
    for(int i = 0; i<[msglist count] ; i++){
        Message *mesg = nil;
        @try {
            if (![MessageDao isExistMessageById:[[msglist objectAtIndex:i] objectForKey:@"id"]]) {
                mesg = [MessageSessionDao updataDBwithSQLiteStatement:[msglist objectAtIndex:i] ];
            }

        }
        @catch (NSException *exception) {
            NSLog(@"mqtt info jiexi err=%@",exception);
        }
        @finally {
            if(mesg){
                [DE dealRecvMessage:mesg];
                [receiptMsgIDs addObject:mesg.mID];
                // 如果为注销命令，则不再继续签收
                if([@"login_destory" isEqualToString:[mesg getValue:@"businessId"] ])
                {
                    [DE recepitMsg:receiptMsgIDs ];
                }
            }
        }

    }
    [DE recepitMsg:receiptMsgIDs ];
    
}

#pragma mark - MQ Delegate

- (void) didConnect:(NSUInteger)code {
    kAppDelegate.mqttState = MQTT_CONNECTTED;
    NSLog(@"MQ is didConnected<<<<<<<< %@",[MsgEngine geMessageClientID]);
    [mosquittoClient subscribe:[MsgEngine geMessageClientID]];
    
}

-(void)reconnect_fun
{
    [self reconnect];
}

- (void) didDisconnect {
    NSLog(@"MQ is didDisconnect....NONONO!!!...");
    if (kAppDelegate.mqttState ==MQTT_CONNECTTED)
    {
        kAppDelegate.mqttState = MQTT_NO_CONNECT;
        [self performSelector:@selector(reconnect_fun) withObject:nil afterDelay:5.0f];
    }
}

- (void) didReceiveMessage:(MosquittoMessage*) mosq_msg {
    
     kAppDelegate.mqttState = MQTT_CONNECTTED;
     if ( mosq_msg && [mosq_msg.payload length] > 0 )
    {
        [self recvMqttMessage:mosq_msg.payload];
    }
	
}

- (void) didPublish: (NSUInteger)messageId {}
- (void) didSubscribe: (NSUInteger)messageId grantedQos:(NSArray*)qos {}
- (void) didUnsubscribe: (NSUInteger)messageId {}

#pragma mark - propertys

-(NSString*)msgServerName
{
    return _msgServerName;
}

-(NSString*)msgServerPort
{
    return _msgServerPort;
}

-(void)setMsgServerName:(NSString *)msgServerName
{
    _msgServerName = msgServerName;
    [_msgServerName retain];
}

-(void)setMsgServerPort:(NSString *)msgServerPort
{
    _msgServerPort = msgServerPort;
    [_msgServerPort retain];
}

//-(NSString*)msgClientId
//{
//    NSString* clientId = [NSString stringWithFormat:@"csu_%@",DE.userId];
//    
//    if([clientId length]>20)
//        return [clientId substringToIndex:20];
//    else
//        return clientId;
//}

+(NSString*) geMessageClientID{
    
//    NSString *fileUserId = [DE getGlobalVar:LOGIN_USER_ID];
    NSString* clientId = [NSString stringWithFormat:@"csu_%@",DE.userId];
    if([clientId length]>20)
        return [clientId substringToIndex:20];
    else
        return clientId;
}

@end
